<?php

namespace app\api\controller;

use app\common\controller\Api;
use fast\Http;
use app\admin\model\Gpswarning as GpswarningModel;
use app\admin\model\Gpswarningaction as GpswarningactionModel;
use app\admin\model\Gpswarningtask as GpswarningtaskModel;
use app\admin\model\Gpswarninglogs as GpswarninglogsModel;
use app\admin\model\cms\Archives;
use app\admin\model\cms\Channel;
use think\Db; 
use addons\weixin\library\WechatService;
use app\admin\model\weixin\User as WechatUser;
use app\admin\model\weixin\template\Wechat as WechatTemplate;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }


    //同步光速报警
    public function sysnGsAlarm(){  
        //执行推送
        $this->pushTaskAction();

        return;
        set_time_limit(45);
        $data = array();
        $data['Action'] = 'GetVehicleGpsInfo';
        $data['UserId'] = '光速监控';
        $data['Pwd'] = strtoupper(md5('gsjk123'));
        $data['Vehicles'] = '';
        $data['NeedAddress'] = '1';
        $json = json_encode($data); 
        $url = 'http://218.5.10.82:800/TopGps/Services/TopDataService.ashx?request='.$json; 
        // echo ;
        $result = file_get_contents($url);
        $res = json_decode($result,true);
        $list = $res['Data'];
        echo json_encode($list); 
        if($list){
            foreach ($list as $key => $value) {
                if($value['AlarmInfo']){
                    $data = array();
                    $data['platenum'] = $value['PlateNum'];
                    $data['gpstime'] = strtotime($value['GpsTime']);
                    if(!GpswarningModel::where($data)->find()){
                        $data['longitude'] = $value['Longitude'];
                        $data['latitude'] = $value['Latitude'];
                        $data['address'] = $value['Address'];
                        $data['alarminfo'] = $value['AlarmInfo'];
                        $data['alarmcontent'] = json_encode($value);
                        $data['source'] = '光速监控';
                        $data['createtime']= time();
                        GpswarningModel::insert($data);

                        if( ($value['AlarmInfo']=='疲劳驾驶(平台);')||($value['AlarmInfo']=='超速报警;') || ($value['AlarmInfo']=='疲劳驾驶;')){
                            //新增汇总逻辑及报警数据
                            unset($data['gpstime']);
                            unset($data['longitude']);
                            unset($data['latitude']);
                            unset($data['alarmcontent']);
                            unset($data['source']);
                            $data['updatetime'] = time();
                            $data['times'] = 1;
                            //获取车牌号、报警信息相同的最后一条数据
                            $result = GpswarningactionModel::where(['platenum'=>$value['PlateNum'],'alarminfo'=>$value['AlarmInfo']])->order("id desc")->find();
                            if($result){
                                //如果当前时间减去上次报警时间间隔小于120秒 则更新当前数据的报警次数  报警位置
                                $d = time() - $result['updatetime'];
                                if( $d < 185 && $result['times'] < 60 ){
                                    $times = $result['times']+1; 
                                    $dt =['times'=>$times,'address'=>$value['Address'],'updatetime'=>time()]; 
                                    if( ($times > 1) && ($times < 10) && ($result['status'] == 0) ){
                                        //如果次数>5次   生成报警任务 插入报警任务表数据  触发status = 1;
                                        $dt['status'] = 1;
                                        //新增微信推送任务表 
                                        $targetAddress = $this->getTargetAddress( $value['PlateNum'], 'Wechat' );
                                        GpswarningtaskModel::insert(['platenum'=>$value['PlateNum'],'type'=>'Wechat','targetAddress'=>$targetAddress,'address'=>$value['Address'],'alarminfo'=>$value['AlarmInfo'],'speed'=>$value['Speed'],'createtime'=>time(),'source'=>'光速监控']); 

                                    }else if( ($times >= 10) && ($times < 25) && ($result['telstatus'] == 0) ){
                                        $dt['telstatus'] = 1; 
                                        $targetAddress = $this->getTargetAddress( $value['PlateNum'], 'Phone' );
                                        //新增微信推送任务表 
                                        GpswarningtaskModel::insert(['platenum'=>$value['PlateNum'],'type'=>'Phone','targetAddress'=>$targetAddress,'address'=>$value['Address'],'alarminfo'=>$value['AlarmInfo'],'speed'=>$value['Speed'],'createtime'=>time(),'source'=>'光速监控']);
                                    }else if( ($times > 25)  && ($result['smsstatus'] == 0)){
                                        $dt['smsstatus'] = 1; 
                                        //新增微信推送任务表 
                                        GpswarningtaskModel::insert(['platenum'=>$value['PlateNum'],'type'=>'Sms','address'=>$value['Address'],'alarminfo'=>$value['AlarmInfo'],'speed'=>$value['Speed'],'createtime'=>time(),'source'=>'光速监控']);
                                    }
                                    GpswarningactionModel::where(['id'=>$result['id']])->update($dt); 
                                }else{
                                    //否则就插入新的报警数据 
                                    GpswarningactionModel::insert($data); 
                                }
                            }else{
                                //插入新的保金数据
                                GpswarningactionModel::insert($data);  
                            } 
                        }  
                    }   
                }
            }
        }  
    }

    /**
     * 推送电话报警信息
     * @ApiMethod   (POST) 
     * @ApiParams   (name="targetAddress", type="integer", required=true, description="推送地址") 
     * @ApiParams   (name="content", type="string", required=true, description="推送内容")  
     */
    public function sendCallMsg(){
         try {   

            $targetAddress = $this->request->param("targetAddress", ''); 
            $content = $this->request->param("content", '');  

               //拨打指定电话 
            $url = "http://47.107.33.193:29003/api/ola/agents/1001/play_audio"; 
            $dd = array();
            $dd['numbers'] = $targetAddress;
            $dd['batch_accept'] = '20190301';
            $dd['filetype'] = 'text';
            $dd['file'] = str_replace([")", "("], ',', $content);
            $dd['gateway'] = '99999'; 
            $rt = Http::sendRequest($url, $dd, 'PUT');
            $rescontent = $rt['msg']; 
            $d = json_decode($rescontent,true);

            $this->success('提交成功',$d); 

        } catch (Exception $e) {
            $this->error('返回失败；'.$e->getMessage());
        }
        
    }

    /**
     * 推送公众号报警信息
     * @ApiMethod   (POST) 
     * @ApiParams   (name="account", type="string", required=true, description="GPS用户名") 
     * @ApiParams   (name="alarmType", type="string", required=true, description="报警类型")  
     * @ApiParams   (name="content", type="string", required=true, description="推送内容")  
     */
    public function OfficialAccounts(){

        $account = $this->request->param("account", ''); 
        $alarmType = $this->request->param("alarmType", ''); 
        $content = $this->request->param("content", '');  

        $data = array(
         'first' => '您的设备有新的报警',
         'keyword1' => $alarmType,
         'keyword2' => '车辆报警',
         'keyword3' => date('Y-m-d H:i:s', time()),
         'keyword4' => $content,
         'remark' => '请关注并及时处理您的设备报警'
        );
        try {
            $userInfo = Db::table('fa_user')->where(['mobile'=>$account])->find();
           
            if($userInfo&&$account){
                $uid = $userInfo['id'];
                $openId = WechatUser::uidToOpenid($uid, 'openid');
                $tempid = WechatTemplate::tempkeyToTempid('DEVICE_ALARM') ?: '3ovggzn7N_uMPM1Ao7PHKmJePImj_c1Zwezgi82ngPs';
                $result = WechatService::sendTemplate($openId, $tempid, $data);
            }else{ 
                $this->error('该用户未绑定公众号平台');
            }
        } catch (Exception $e) {
            
            $this->error($e->getMessage());
        }
        
        if(isset($result['errcode']) && $result['errcode'] === 0){
            $this->success('发送成功');
        } 
    }


    /**
     * 推送报警信息
     * @ApiMethod   (POST) 
     * @ApiParams   (name="targetAddress", type="integer", required=true, description="推送地址") 
     * @ApiParams   (name="content", type="string", required=true, description="推送内容")  
     */
    public function sendWechatMsg(){
         try {   

            $targetAddress = $this->request->param("targetAddress", ''); 
            $content = $this->request->param("content", '');  

            //拨打指定电话 
            $url = "http://wx.350gps.cn/zt/api.php"; 
            $dd = array();
            $dd['to_wxid'] = $targetAddress;
            $dd['msg'] = $content; 
            $dd['act'] = 'send_msg';
            Db::startTrans();
            if($targetAddress != '20111480336@chatroom'){  
                try {
                     if(!GpswarninglogsModel::where(['sendMsg'=>$content])->find()){
                        $rt = Http::sendRequest($url, $dd, 'GET');
                        $rescontent = $rt['msg'];  
                        $d = json_decode($rescontent,true);

                        //插入发送记录表
                        $params = array();
                        $params['platenum'] = '--';
                        $params['targetAddress'] = $targetAddress;
                        $params['sendtype'] = "Wechat";
                        $params['sendMsg'] = $content;
                        $params['status'] = 1;
                        $params['rescontent'] = $rescontent;
                        $params['createtime'] = time();
                        if($d['code'] == '0'){
                            $params['status'] = 1;
                        }
                        GpswarninglogsModel::insert($params);
                        Db::commit();

                        // sleep(1);
                    } 
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error('操作异常'); 
                }
               
            }
            $this->success('提交成功'); 

        } catch (Exception $e) {
            $this->error('返回失败；'.$e->getMessage());
        }
        
    }

    /**
     * 获取推送群组列表
     * @ApiMethod   (POST)  
     */
    public function getWechatList(){
         try {    
            //拨打指定电话 
            $url = "http://wx.350gps.cn/zt/api.php"; 
            $dd = array(); 
            $dd['act'] = 'get_group_list';
            $rt = Http::sendRequest($url, $dd, 'GET');
            $rescontent = $rt['msg']; 
            $d = json_decode($rescontent,true);
            $this->success('提交成功',$d);  
        } catch (Exception $e) {
            $this->error('返回失败；'.$e->getMessage());
        }
        
    }
    /**
     * 添加报警任务
     * @ApiMethod   (POST)
     * @ApiParams   (name="platenum", type="string", required=true, description="platenum车牌号")
     * @ApiParams   (name="type", type="string", required=true, description="微信：Wechat 手机：Phone 短信：Sms") 
     * @ApiParams   (name="targetAddress", type="integer", required=true, description="推送地址") 
     * @ApiParams   (name="address", type="string", required=true, description="报警所在地地址") 
     * @ApiParams   (name="alarminfo", type="string", required=true, description="报警标识") 
     * @ApiParams   (name="source", type="string", required=true, description="报警来源") 
     */
    public function addTaskAction(){
         try {  
            exit;
            
            
            $platenum = $this->request->param("platenum", '');
            $type = $this->request->param("type", 'Wechat');  
            $targetAddress = $this->request->param("targetAddress", ''); 
            $address = $this->request->param("address", ''); 
            $source = $this->request->param("source",'');

            $alarminfo = $this->request->param("alarminfo", ''); 

            if($targetAddress != '20111480336@chatroom'){
            // $address = "测试目标地址";
            // if($alarminfo == '超速报警' || $alarminfo=='疲劳报警' ){
                $res = GpswarningtaskModel::insert(['platenum'=>$platenum,'type'=>$type,'targetAddress'=>$targetAddress,'address'=>$address,'alarminfo'=>$alarminfo,'createtime'=>time(),'source'=>$source]);
                if($res){ 
                    $this->success('提交成功'); 
                }else{ 
                    $this->error('提交失败'); 
                }
            // }
            //   
            }
        } catch (Exception $e) {
            $this->error('返回失败；'.$e->getMessage());
        }
        
    }


    public function pushTaskAction(){
        // return;
        $this->callPhone();
        $list = GpswarningtaskModel::where(['status'=>0,'type'=>'Wechat'])->order("id asc")->select();
        if($list){ 
            foreach ($list as $key => $value) {
                $this->sendWechat($value);
            }
        }
    }
     /**
     * 定时任务执行报警任务  
     */ 
    private function sendWechat($result){
        // $result = GpswarningtaskModel::where(['status'=>0])->order("id asc")->find();
        if($result){ 
            $c = floor((time()-$result['createtime'])%86400/60);
            $targetAddress = $this->getTargetAddress( $result['platenum'], $result['type'] );
            $content = "您请注意！贵公司车辆".trim($result['platenum'])."在".trim($result['address'])."产生【".trim($result['alarminfo'])."速度".$result['speed']."码】的报警信息。";
            if( $result['type'] == 'Wechat' ){ 
                //执行发送任务
                // $targetAddress = "20111480336@chatroom";
                //拨打指定电话 
                $url = "http://wx.350gps.cn/zt/api.php"; 
                $dd = array();
                $dd['to_wxid'] = $result['targetAddress'];
                $dd['msg'] = $content; 
                $dd['act'] = 'send_msg';
                $rt = Http::sendRequest($url, $dd, 'GET');
                $rescontent = $rt['msg']; 
                $d = json_decode($rescontent,true);
                //插入发送记录表
                $params = array();
                $params['platenum'] = $result['platenum'];
                $params['targetAddress'] = $result['targetAddress'];
                $params['sendtype'] = "Wechat";
                $params['sendMsg'] = $content;
                $params['status'] = 1;
                $params['rescontent'] = $rescontent;
                $params['createtime'] = time();
                if($d['code'] == '0'){
                    $params['status'] = 1;
                }
                GpswarninglogsModel::insert($params);
                //更新当前任务发送状态
                GpswarningtaskModel::where(['id'=>$result['id']])->update(['status'=>1,'updatetime'=>time()]); 
            }
            // else if( $result['type'] == 'Phone' ){

              
            // }else if( $result['type'] == 'Sms' ){
            //     //发送短信 
                 
            //     GpswarningtaskModel::where(['id'=>$result['id']])->update(['status'=>1,'updatetime'=>time()]);  
            // }

        }

    }

    private function callPhone(){
        $result = GpswarningtaskModel::where(['status'=>0,'type'=> 'Phone'])->order("id asc")->find();
        if($result){ 
            GpswarningtaskModel::where(['id'=>$result['id'],'type'=> 'Phone'])->update(['status'=>1,'updatetime'=>time()]);  
                // exit;
                //拨打指定电话 
            $url = "http://47.107.33.193:29003/api/ola/agents/1001/play_audio"; 
            $dd = array();
            $dd['numbers'] = $result['targetAddress'];
            $dd['batch_accept'] = '20190301';
            $dd['filetype'] = 'text';
            $dd['file'] = str_replace([")", "("], ',', $content);
            $dd['gateway'] = '99999'; 
            $rt = Http::sendRequest($url, $dd, 'PUT');
            $rescontent = $rt['msg']; 
            $d = json_decode($rescontent,true);
            if($d['code'] == '200'){
                $params['status'] = 1;
            } 
            $params['rescontent'] = $rescontent;  
            $params = array();
            $params['platenum'] = $result['platenum'];
            $params['targetAddress'] = $result['targetAddress'];
            $params['sendtype'] = "Phone";
            $params['sendMsg'] = $content;
            $params['status'] = 1;
            $params['rescontent'] = $rescontent;
            $params['createtime'] = time();
            GpswarninglogsModel::insert($params);
            //更新当前任务发送状态
            GpswarningtaskModel::where(['id'=>$result['id'],'type'=> 'Phone'])->update(['status'=>1,'updatetime'=>time()]);  
        }

    }

    //获取目标地址
    private function getTargetAddress($platenum,$type){
        if($type == 'Wechat'){
            //通过车牌号获取车牌号绑定的推送地址
            $platenumWechat = Archives::where('title',$platenum)->find();
            $targetAddress = $platenumWechat['keywords'];
            if(!$targetAddress){
                //如果车牌没设置推送地址则读取车组的
                $channelWechat = Channel::get($platenumWechat['channel_id']);
                $targetAddress = $channelWechat['keywords'];
            }
            return $targetAddress;
        }else if($type ='Phone'){
            $platenumPhone = Archives::where('title',$platenum)->find();
            $targetAddress = $platenumPhone['seotitle'];
            if(!$targetAddress){
                //如果车牌没设置推送地址则读取车组的
                $channelPhone = Channel::get($platenumPhone['channel_id']);
                $targetAddress = $channelPhone['seotitle'];
            }
            return $targetAddress;
            // return '15659124787';
        }
    }

    public function test($platenum='闽AQ3251',$type='Wechat'){
        var_dump($this->getTargetAddress($platenum,$type));
    }

}
